<template>
  <view class="container">
    <uni-forms ref="form" :modelValue="formData" labelWidth="120px" labelPosition="top">
      <view class="hidden-title">信息填写</view>
      <cu-cell-group>
        <uni-forms-item name="deptId">
          <cu-cell
            title="所属部门"
            required
            link
            placeholder="请选择所属部门"
            :description="formData.deptName"
            @click="handleDeptClick()"
          />
        </uni-forms-item>
        <uni-forms-item name="managerType">
          <cu-cell
            title="隐患类型"
            required
            link
            placeholder="请选择隐患类型"
            :description="formData.managerTypeLabel"
            @click="managerTypeClick()"
          ></cu-cell>
        </uni-forms-item>
        <uni-forms-item name="managerLevel">
          <cu-cell
            title="隐患级别"
            required
            link
            placeholder="请选择隐患级别"
            :description="formData.managerLevelLabel"
            @click="managerLevelClick()"
          ></cu-cell>
        </uni-forms-item>
        <uni-forms-item name="majorHiddenDangerType" v-if="importantDangerValue == formData.managerLevel">
          <cu-cell
            title="重大隐患判定依据"
            required
            link
            placeholder="请选择重大隐患判定依据"
            :description="majorHiddenDangerName"
            @click="dangerSourceClick()"
          ></cu-cell>
        </uni-forms-item>
      </cu-cell-group>
      <view class="background-white bor-top">
        <uni-forms-item name="managerDesc" label="隐患描述">
          <textarea
            v-model="formData.managerDesc"
            class="text-area"
            placeholder="对发生的隐患进行简要描述,方便治理人员快速判断需要做的准备(限100字)"
            placeholder-class="form-placeholder__style"
            maxlength="100"
          />
        </uni-forms-item>
      </view>
      <view class="background-white bor-top" v-if="formData.managerSource == managerSourceEnum.ONTHEGO">
        <uni-forms-item name="location" label="隐患位置">
          <textarea
            v-model="formData.location"
            class="text-area"
            placeholder="请输入隐患位置信息(限50字)"
            placeholder-class="form-placeholder__style"
            maxlength="50"
          />
        </uni-forms-item>
      </view>

      <view class="background-white bor-top bottom">
        <uni-forms-item name="reportPhotoUrl" label="上传照片（最多3张）" labelWidth="150">
          <image-upload state="edit" :imageUrl="formData.reportPhotoUrl" @change="imageOnChange"> </image-upload>
        </uni-forms-item>
      </view>
      <view class="submit-group">
        <button class="u-button block" :ripple="true" @click="submit">上报</button>
      </view>
    </uni-forms>

    <dept-selector ref="deptSelectorRef" @change="onDeptSelectorChange" />
    <dict-picker ref="managerTypeDict" title="隐患类型" dictType="dbd_manager_type" @confirm="manageTypeOnConfirm">
    </dict-picker>
    <dict-picker ref="managerLevelDict" title="隐患级别" dictType="dbd_manager_level" @confirm="manageLevelOnConfirm">
    </dict-picker>
    <manager-level-picker
      ref="managerLevelPicker"
      title="重大隐患判定依据"
      :data="managerLevelList"
      @confirm="managerLevelConfirm"
    ></manager-level-picker>
  </view>
</template>

<script>
import { getRiskAreaList, getDangerSourceList } from '@/api/dbd/hiddenDangerCheck.js'
import { report, reportCheck, getMajorHiddenDangerType, distributeTask } from '@/api/dbd/hiddenDangerReport.js'
import { getDicts } from '@/api/system/dict.js'
import { occupy, cancel } from '@/api/dbd/controlCheck.js'

import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import DictPicker from '@/components/dict-picker/index.vue'
import DataPicker from '@/components/data-picker/index.vue'
import ImageUpload from '@/components/image-upload/index.vue'
import { mapMutations } from 'vuex'

import ManagerLevelPicker from '../components/ManagerLevelPicker.vue'
import { managerSourceEnum } from '@/utils/constant.js'
import DeptSelector from '@/components/dept-selector/index.vue'
export default {
  components: {
    DeptSelector,
    CuCellGroup,
    CuCell,
    DictPicker,
    DataPicker,
    ImageUpload,
    ManagerLevelPicker
  },
  data() {
    return {
      managerSourceEnum,
      //1点检场所 2点检设备 3润滑 4维保
      reportType: '',
      formData: {
        //隐患项
        mangerName: '',
        //隐患类型
        managerType: '',
        //隐患级别
        managerLevel: '',
        //所属风险区域
        areaId: null,
        //所属重大危险源
        dangerSourceId: null,
        // 隐患位置
        location: '',
        //隐患描述
        managerDesc: '',
        // 隐患分析
        managerAnalysis: '',
        // 默认隐患来源是“随手拍”1
        managerSource: managerSourceEnum.ONTHEGO, //11管控排查 12隐患排查
        // 现场照片
        reportPhotoUrl: '',
        // 隐患排查子任务id
        dangerPlanSubTaskId: null,
        // 管控排查任务id
        checkPlanTaskId: null,

        // 重大隐患判定依据id
        majorHiddenDangerType: '',

        // 重大隐患判定依据
        majorManagerCriteria: '',
        managerSourceId: '',
        managerTypeLabel: '',
        managerLevelLabel: '',
        troubleshooting: '',

        // 所属部门
        deptName: '',
        deptId: ''
      },
      rules: {
        managerType: {
          rules: [
            {
              required: true,
              errorMessage: '隐患类型不能为空'
            }
          ]
        },
        deptId: {
          rules: [
            {
              required: true,
              errorMessage: '所属部门不能为空'
            }
          ]
        },
        managerLevel: {
          rules: [
            {
              required: true,
              errorMessage: '隐患级别不能为空'
            }
          ]
        },
        managerDesc: {
          rules: [
            {
              required: true,
              errorMessage: '隐患描述不能为空'
            }
          ]
        },
        location: {
          rules: [
            {
              required: true,
              errorMessage: '隐患位置不能为空'
            }
          ]
        },
        majorHiddenDangerType: {
          rules: [
            {
              required: true,
              errorMessage: '重大隐患判定依据不能为空'
            }
          ]
        },
        reportPhotoUrl: {
          rules: [
            {
              required: true,
              errorMessage: '照片不能为空'
            }
          ]
        }
      },
      riskAreaList: [],
      dangerSourceList: [],
      managerTypeLabel: '',
      managerLevelLabel: '',
      dangerSourceLabel: '',
      riskAreaLabel: '',
      DBDManagerLevelList: [], // 隐患级别列表
      activeLevel: undefined, // 当前选中的隐患级别
      managerLevelList: [],
      importantDangerValue: '',
      // 重大安全隐患名
      majorHiddenDangerName: ''
    }
  },
  // computed: {
  // 	...mapState({
  // 		detail: (state) => state.detail
  // 	}),
  // },
  onLoad(option) {
    this.subTaskId = option.subTaskId
    this.index = option.index
    this.reportType = option.reportType
    // 设备预防性维护
    if (option.areaId) {
      this.formData.areaId = option.areaId
      this.formData.sourceType = '16'
    }
    if (option.managerSource) {
      this.formData.managerSource = String(option.managerSource)
      if (option.managerSource === managerSourceEnum.HIDDENDANGER) {
        this.formData.planSubTaskId = this.formData.dangerPlanSubTaskId = option.subTaskId
        this.formData.planTaskId = option.managerSourceId
      } else if (option.managerSource === managerSourceEnum.CONTROL) {
        this.formData.checkPlanTaskId = option.planTaskId
      }
      this.formData.location = option.location || ''
      this.formData.mangerName = option.riskName || ''
      this.formData.managerSourceId = option.managerSourceId || ''
    }
    if (option.deptId) {
      this.formData.deptId = option.deptId
      this.formData.deptName = option.deptName
    }
    if (option.troubleshooting) {
      this.formData.troubleshooting = option.troubleshooting
    }
    this.getRiskAreaData()
    this.getDangerSourceData()
    this.getDBDManagerLevelList()
    this.getManagerLevelList()
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  // onShow() {
  // 	this.formData = this.$store.hiddenDangerInfo.state.detail
  // },
  beforeDestroy() {
    //this.cancel();
  },
  methods: {
    ...mapMutations(['setHiddenDangerInfo', 'clearHiddenDangerInfo']),
    occupy() {
      occupy(this.formData.checkPlanTaskId).then((res) => {
        console.log('任务占用成功')
      })
    },
    cancel() {
      if (this.formData.checkPlanTaskId) {
        cancel(this.formData.checkPlanTaskId).then((res) => {
          console.log('任务占用取消成功')
        })
      }
    },
    managerLevelConfirm(obj) {
      this.formData.majorHiddenDangerType = obj.value
      // this.formData.managerDesc = obj.name
      this.formData.majorManagerCriteria = obj.name
      this.majorHiddenDangerName = obj.name
    },
    getManagerLevelList() {
      getMajorHiddenDangerType().then((res) => {
        this.managerLevelList = res.data
      })
    },
    navigateBack() {
      uni.navigateBack()
    },
    // 获取隐患级别
    getDBDManagerLevelList() {
      getDicts('dbd_manager_level').then((res) => {
        this.DBDManagerLevelList = res.data
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].dictLabel == '一般隐患') {
            this.managerLevelLabel = res.data[i].dictLabel
            // this.formData.managerLevel = res.data[i].dictValue
          }
          if (res.data[i].dictLabel == '重大隐患') {
            this.importantDangerValue = res.data[i].dictValue
          }
        }
      })
    },
    /**
     * 部门点击事件
     */
    handleDeptClick() {
      this.$refs.deptSelectorRef.open()
    },
    /**
     * 部门选择事件
     */
    onDeptSelectorChange({ name, value }) {
      this.formData.deptName = name
      this.formData.deptId = value
    },
    managerTypeClick() {
      this.$refs.managerTypeDict.open()
    },
    manageTypeOnConfirm(obj) {
      this.formData.managerTypeLabel = obj.name
      this.formData.managerType = obj.value
    },
    managerLevelClick() {
      this.$refs.managerLevelDict.open()
    },
    manageLevelOnConfirm(obj) {
      this.formData.managerLevelLabel = obj.name
      this.formData.managerLevel = obj.value
      // this.rules.dangerSource.rules[0].required = obj.name === '重大隐患'
      // this.$nextTick(() => {
      // 	this.$refs.form.setRules(this.rules)
      // })
    },
    getRiskAreaData() {
      getRiskAreaList(this.pageNum).then((res) => {
        this.riskAreaList = res.rows.map((val, index) => {
          return {
            name: val.areaName,
            value: val.areaId
          }
        })
      })
    },
    riskAreaClick() {
      this.$refs.riskAreaPicker.open()
    },
    riskAreaOnConfirm(obj) {
      this.riskAreaLabel = obj.name
      this.formData.areaId = obj.value
    },
    getDangerSourceData() {
      getDangerSourceList().then((res) => {
        this.dangerSourceList = res.rows.map((val, index) => {
          return {
            name: val.dangerName,
            value: val.infoId
          }
        })
      })
    },
    dangerSourceClick() {
      this.$refs.managerLevelPicker.open()
    },
    dangerSourceOnConfirm(obj) {
      this.dangerSourceLabel = obj.name
      this.formData.dangerSourceId = obj.value
    },
    imageOnChange(urlList) {
      this.formData.reportPhotoUrl = urlList.join(',')
    },
    submit() {
      this.$refs.form.validate().then((res) => {
        this.$modal.confirm('确定上报隐患？').then(() => {
          let fn = report // 隐患排查上报
          switch (this.formData.managerSource) {
            case managerSourceEnum.CONTROL:
              fn = reportCheck // 管控排查上报
              break
            case managerSourceEnum.DEVICEINSPECT:
            case managerSourceEnum.ONTHEGO:
              fn = distributeTask // 设备预防性维护 随手拍
              break
            default:
              break
          }

          fn.call(null, this.formData).then((res) => {
            this.$modal.showToast('上报成功')
            // 调用正常接口
            this.checkNormal()
          })
        })
      })
    },
    distribute() {
      this.$refs.form.validate().then((res) => {
        this.setHiddenDangerInfo(this.formData)
        let that = this
        uni.navigateTo({
          url: `/pages/work/hiddenDangerReport/components/distributeTask?reportType=${this.reportType}`,
          events: {
            // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
            'callback:report': () => {
              if (that.reportType) {
                const eventChannel = that.getOpenerEventChannel()
                eventChannel.emit('callback:success')
                uni.navigateBack()
              }
            }
          }
        })
      })
    },
    checkNormal() {
      // if (!this.formData.dangerPlanSubTaskId) {
      //   uni.navigateBack()
      //   return
      // }
      this.$modal.showToast('已经完成隐患任务的排查')
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('callback:success', {
        subTaskId: this.subTaskId,
        index: this.index
      })
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.container {
  .background-white {
    background-color: #fff;
    padding: 20rpx 30rpx;
    box-sizing: border-box;

    .uni-forms-item__label {
      color: #333;
      font-size: 30rpx;
    }

    .bor-btm {
      display: flex;
      border-bottom: 1px solid #d5d7e3;
    }

    .photo {
      display: flex;
      justify-content: space-between;

      image {
        width: 214rpx;
        height: 214rpx;
      }
    }
  }
}

.hidden-title {
  background: #f5f5f5;
  padding: 20rpx;
  color: #999;
}

.bor-top {
  border-top: 20rpx solid #f5f5f5;
}

.bottom {
  margin-bottom: 120px;
}
</style>
